package com.mmall.controller;

import com.mmall.common.ServerResponse;
import com.mmall.pojo.Address;
import com.mmall.pojo.User;
import com.mmall.service.AddressService;
import com.mmall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("address/")
public class AddressController {


    @Autowired
    private AddressService addressService;

    @Autowired
    private UserService userService;
    @RequestMapping(value = "create.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse create(Address address,String loginToken){
        ServerResponse response = userService.userIsLogin(loginToken);
        if(!response.isSuccess()){
            return response;
        }
        User user = (User)response.getData();
        address.setUserId(user.getId());
        return addressService.insert(address,user.getId());
    }

    @RequestMapping(value = "update.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse update(Address address,String loginToken){
        ServerResponse response = userService.userIsLogin(loginToken);
        if(!response.isSuccess()){
            return response;
        }
        User user = (User)response.getData();
        return addressService.update(address,user.getId());
    }


    @RequestMapping(value = "find.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse find(Integer id){
        return addressService.select(id);
    }

    @RequestMapping(value = "delete.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse delete(Integer id,String loginToken){
        ServerResponse response = userService.userIsLogin(loginToken);
        if(!response.isSuccess()){
            return response;
        }
        return addressService.delete(id);
    }

    @RequestMapping(value = "findAddressList.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse findAddressList(String loginToken){
        ServerResponse response = userService.userIsLogin(loginToken);
        if(!response.isSuccess()){
            return response;
        }
        User user = (User)response.getData();
        return addressService.findAddressListByUserId(user.getId());
    }
}
